package com.yunao.web.thread;

import com.yunao.entity.AloneReport;
import com.yunao.service.AlonereportService;
import com.yunao.service.ReportService;
import com.yunao.service.report.esou.ReportThread2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 自动报告线程
 */
@EnableScheduling
@Component
public class AutoReportThread {

    private static Logger logger = LoggerFactory.getLogger(AutoReportThread.class);

    @Autowired
    private AlonereportService alonereportService;
    @Autowired
    private ReportService reportService;
    private int MaxThread = 15;//最大线程数

    @Scheduled(cron ="0 0/30 19 * * ?")//cron ="0 0/30 19 * * ?"每天下午7点-8点 每30分钟一次 共1次
    public void run(){
        logger.info("正在生成自动报告...");
        // 所有需要使用自动报告的专题
        List<AloneReport> aloneReports = alonereportService.findByNeed("1");
        // 预警专题数
        int total = aloneReports.size();
        // 线程池
        ExecutorService pool = Executors.newCachedThreadPool();

        int len=MaxThread;
        int avg=total/len;
        if(avg==0)
        {
            len=total;
            avg=1;
        }
        for (int i = 0; i < len; i++) {
            int fromIndex = i * avg;
            int toIndex = i == len - 1 ? total : fromIndex + avg;
            pool.execute(new ReportThread2(aloneReports.subList(fromIndex, toIndex),reportService));
        }
        //线程池关闭
        pool.shutdown();
    }

}
